package com.kh.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kh.reggie.common.Result;
import com.kh.reggie.entity.Category;
import com.kh.reggie.entity.Employee;
import com.kh.reggie.mapper.CategoryMapper;
import com.kh.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 分类管理
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController{

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody Category category){
        log.info("category:{}",category);
        categoryService.save(category);
        return Result.success("新增分类成功");
    }

    /**
     * 分类分页查询
     * @param page
     * @param pageSize
     *
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize){
        log.info("page = {},pageSize = {},name = {}" ,page,pageSize);
//        分页构造器
        Page pageInfo = new Page(page,pageSize);
//        条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper();
//        添加排序条件
        queryWrapper.orderByAsc(Category::getSort);
//        执行查询
        categoryService.page(pageInfo,queryWrapper);
        return Result.success(pageInfo);
    }

    @DeleteMapping
    public Result<String> delete(Long id){
        log.info("删除分类");
        categoryService.remove(id);
        return Result.success("删除分类成功");
    }

    /**
     * 根据id修改分类信息
     * @param category
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody Category category){
        log.info("修改分类");
        categoryService.updateById(category);
        return Result.success("修改分类成功");
    }

    /**
     * 根据条件查询分类
     * @param category
     * @return
     */
    @GetMapping("/list")
    public Result<List> listShowCategory(Category category){
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper();
        //MP也支持把对象先判断一下，非空才能进行查询
        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        //lambdaQueryWrapper.eq(Category::getType, category.getType());
        //按时间倒叙排序
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //查询
        List<Category> categoryList = categoryService.list(queryWrapper);
        return Result.success(categoryList);
    }

}
